// components/search/index.js
import { KeywordModel} from '../../models/keyword.js'
import { BookModel } from '../../models/book.js'
import {paginationBev} from '../behaviors/pagination.js'


const bookModel = new BookModel()
const keywordModel = new KeywordModel()

Component({
  /**
   * 组件的属性列表
   */
  //组件可以继承多个behavior，所以这里是behaviors数组
  behaviors: [paginationBev],
  //observer用来监听属性值改变
  properties: {
    more: {
      type:String,
      observer:'loadMore'
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords:[],
    hotWords:[],
    words:'',
    searching: false,
    loadingCenter: false
  },
  attached(){
    this.setData({
      historyWords: keywordModel.getHistory()
    })
    keywordModel.getHotSearch()
    .then(res=>{
      this.setData({
        hotWords: res.hot
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //用户下滑页面到底
    loadMore:function(){
      //判断用户输入是否为空
      if (!this.data.words) {
        return
      }
      //是否正在数据请求中
      if (this.isLocked()) {
        return
      }
      //数据是否还未加载完
      if (this.hasMore()) {
        //数据请求前上锁
        this.locked()
        //请求数据
        bookModel.searchBook(this.getCurrentStart(), this.data.words)
          .then(res => {
            this.setMoreData(res.books)
            //成功时解锁
            this.unLocked()
          }, () => {
            //失败时也解锁否则会变成死锁
            this.unLocked()
          })
      }
    },
    //点击取消
    onCancel:function(){
      //清空上次数据
      this.initialize()
      this.triggerEvent('cancel',{},{})
    },
    //用户回车
    onConfirm:function(event){
      const keyword = event.detail.value || event.detail.text
      //输入为空时直接return
      if (!keyword){
        return
      }
      //清空上次数据
      this.initialize()
      this._showResult()
      this.setData({
        words: keyword
      })
      this._showLoadingCenter()
      //获取搜索图书
      bookModel.searchBook(0, keyword)
      .then(res=>{
        this.setMoreData(res.books)
        this.setTotal(res.total)
        this._hideLoadingCenter()
      })
      //写入搜索历史
      keywordModel.addHistory(keyword)
    },
    //用户点击清空输入
    onDelete:function(){
      this._clearResult()
      //清空上次数据
      this.initialize()
    },
    //显示搜索结果
    _showResult:function(){
      this.setData({
        searching: true
      })
    },
    //清空用户输入，返回搜索页面
    _clearResult:function(){
      this.setData({
        words: '',
        searching: false
      })
    },
    //显示加载中动图
    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },
   //隐藏加载中动图
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    },
  }
})
